#!/bin/sh

count=$(iptables -n -L INPUT 2>/dev/null | grep -c "SSR_LIBEV-SERVER")
if [ -n "$count" ]; then
	until [ "$count" = 0 ]
	do
		rules=$(iptables -n -L INPUT --line-num 2>/dev/null | grep "SSR_LIBEV-SERVER" | awk '{print $1}')
		for rule in $rules
		do
			iptables -D INPUT $rule 2>/dev/null
			break
		done
		count=$(expr $count - 1)
	done
fi

iptables -F SSR_LIBEV-SERVER 2>/dev/null && iptables -X SSR_LIBEV-SERVER 2>/dev/null

enable=$(uci -q get ssr_libev_server.@global[0].enable)
if [ $enable -eq 1 ]; then
	iptables -N SSR_LIBEV-SERVER
	iptables -I INPUT -j SSR_LIBEV-SERVER
	
	count=$(uci show ssr_libev_server | grep "@user" | sed -n '$p' | cut -d '[' -f 2 | cut -d ']' -f 1)
	[ -n "$count" ] && [ "$count" -ge 0 ] && {
		u_get() {
			local ret=$(uci -q get ssr_libev_server.@user[$1].$2)
			echo ${ret:=$3}
		}
		for i in $(seq 0 $count); do
			enable=$(u_get $i enable 0)
			[ $enable -eq 0 ] && continue
			remarks=$(u_get $i remarks)
			port=$(u_get $i port)
			udp_forward=$(u_get $i udp_forward)
			iptables -A SSR_LIBEV-SERVER -p tcp --dport $port -m comment --comment "$remarks" -j ACCEPT
			[ "$udp_forward" = "1" ] && iptables -A SSR_LIBEV-SERVER -p udp --dport $port -m comment --comment "$remarks" -j ACCEPT
		done
	}
fi
